package biznussoft.metercor.lookup;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Set;

import android.app.Dialog;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;
import biznussoft.metercor.R;
import biznussoft.metercor.entity.AccountModel;
import biznussoft.metercor.fragments.AccountDetailsFragment;
import biznussoft.metercor.fragments.AccountsFragment;
import biznussoft.metercor.fragments.ContactDetailsFragment;
import biznussoft.metercor.utils.Session;



public class AccountLookup implements OnItemClickListener {
	LookupAdapter adapter;
	Dialog lookupDialog;
	String strCategory;
	boolean isFiltered;
	private ArrayList<AccountModel> data;  
	private ArrayList<AccountModel> filterList;
	private ListView lvLookup;
	private EditText etLookUp;
	private Context mContext;
	public void accountLookupDetails(Context context,String category){

		strCategory = category;
		mContext = context;
		lookupDialog = new Dialog(context);
		lookupDialog.setContentView(R.layout.accountlookup);
		lookupDialog.setTitle("FieldService360");
		lvLookup = (ListView) lookupDialog.findViewById(R.id.lvAccountlookuplistview);
		etLookUp = (EditText) lookupDialog.findViewById(R.id.etFilteraccount);
		lvLookup.setFastScrollEnabled(true);
		Collections.sort(AccountsFragment.list,new ListComparator());
		adapter = new LookupAdapter(AccountsFragment.list);
		lvLookup.setAdapter(adapter);
		etLookUp.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {

				adapter.getFilter().filter(s);

			}
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}
			public void afterTextChanged(Editable s) {

			}
		});

		lookupDialog.show();



		lvLookup.setOnItemClickListener(this);


	}

	class ListComparator implements Comparator<AccountModel>,Serializable{

		@Override
		public int compare(AccountModel o1, AccountModel o2) {
			return o1.getName().compareToIgnoreCase(o2.getName());
		}

	}

	class LookupAdapter extends BaseAdapter implements Filterable,SectionIndexer{

		private  ValueFilter valueFilter;
		HashMap<String, Integer> alphaIndexer;
		String [] sections;
		ArrayList<AccountModel> mStringFilterList = new ArrayList<AccountModel>();
		public LookupAdapter(ArrayList<AccountModel> list) {


			alphaIndexer = new HashMap<String, Integer>();
			int size = list.size();

			for (int x = 0; x < size; x++) {
				AccountModel s = list.get(x);
				String ch =  s.getName().substring(0, 1);
				//ch = ch.toUpperCase();
				alphaIndexer.put(ch, x);
			}

			Set<String> sectionLetters = alphaIndexer.keySet();

			ArrayList<String> sectionList = new ArrayList<String>(sectionLetters); 

			Collections.sort(sectionList);

			sections = new String[sectionList.size()];

			sectionList.toArray(sections);

			data = list;
			mStringFilterList = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		class ViewHolder{
			public TextView name,age;
		}

		@Override
		public View getView(int position, View v, ViewGroup parent) {
			ViewHolder holder;
			if(v== null){
				holder = new ViewHolder();
				LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(android.R.layout.simple_list_item_1, null);
				holder.name = (TextView) v.findViewById(android.R.id.text1);
				v.setTag(holder);
			}else{
				holder = (ViewHolder) v.getTag();
			}

			AccountModel b = data.get(position);
			holder.name.setText(b.getName());


			return v;
		}


		public Filter getFilter() {
			if(valueFilter==null) {

				valueFilter=new ValueFilter();
			}

			return valueFilter;
		}

		private class ValueFilter extends Filter
		{

			@Override
			protected FilterResults performFiltering(CharSequence constraint)
			{
				FilterResults results=new FilterResults();

				if(constraint!=null && constraint.length()>0){

					filterList=new ArrayList<AccountModel>();

					for(int i=0;i<mStringFilterList.size();i++){

						String mLastName = mStringFilterList.get(i).getName();
						if(mLastName.toLowerCase().contains(constraint.toString()))
						{
							filterList.add(mStringFilterList.get(i));

						}
					}
					results.count=filterList.size();
					results.values=filterList;
					isFiltered = true;
				}else{
					isFiltered = false;
					results.count=mStringFilterList.size();
					results.values=mStringFilterList;

				}

				return results;
			}

			@SuppressWarnings("unchecked")
			@Override
			protected void publishResults(CharSequence constraint,
					FilterResults results) 
			{
				data = (ArrayList<AccountModel>) results.values;

				notifyDataSetChanged();

			}


		}


		public int getPositionForSection(int section) {
			return alphaIndexer.get(sections[section]);
		}

		public int getSectionForPosition(int position) {
			return 1;
		}

		public Object[] getSections() {
			return sections;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {

		switch (arg0.getId()) {           
		case R.id.lvAccountlookuplistview:
			AccountModel bean  = data.get(position);
			if(strCategory.equalsIgnoreCase("Account")){
				AccountDetailsFragment.etParentAccount.setText(bean.getName());}else{
					ContactDetailsFragment.etContactAccountName.setText(bean.getName());
				}
			Session.sParentId=bean.getId();
			lookupDialog.dismiss();
			break;


		default:
			break;
		}

	}
}
